package com.powernode.filter;


import com.alibaba.fastjson.JSONObject;
import com.powernode.constant.AuthConstants;
import com.powernode.model.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Author: Tong Ziyu
 * @Date: 2024/11/6 21:14
 */
@Component
public class TokenAnalysisFilter extends OncePerRequestFilter {
    
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * token转换过滤器
     *    前提: 只负责处理携带token的请求,将认证的用户信息转换出来
     *    没有携带token的请求,交给了security框架去处理
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 从请求头中获取到token
        String token = request.getHeader(AuthConstants.AUTHORIZATION);

        if (StringUtils.hasText(token)){
            token = token.replace(AuthConstants.BEARER, "");

            if (StringUtils.hasText(token)){

                // 解决token续签
                Long expire = stringRedisTemplate.getExpire(AuthConstants.LOGIN_TOKEN_PREFIX + token);

                if (expire <= AuthConstants.TOKEN_EXPIRE_THRESHOLD_TIME){
                    stringRedisTemplate.expire(AuthConstants.LOGIN_TOKEN_PREFIX + token, AuthConstants.TOKEN_TIME, TimeUnit.SECONDS);
                }


                // 有token,从redis中获取token
                String userJson = stringRedisTemplate.opsForValue().get(AuthConstants.LOGIN_TOKEN_PREFIX + token);

                // 将字符串转成UserDetails对象
                SecurityUser userDetails = JSONObject.parseObject(userJson, SecurityUser.class);

                // 将认证对象放到容器中
                SecurityContext context = SecurityContextHolder.getContext();

                // 处理用户权限
                Set<String> perms = userDetails.getPerms();

                Set<GrantedAuthority> authorities = new HashSet<>();

                for (String str : perms){

                    SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(str);
                    authorities.add(simpleGrantedAuthority);
                }


                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                        new UsernamePasswordAuthenticationToken(userDetails,null, authorities);

                // 将认证对象放到Security上下文中,后续可以直接从Security上下文中获取当前登录对象
                context.setAuthentication(usernamePasswordAuthenticationToken);

            }
        }
        /**
         * 分析:
         *  - 这个是资源服务器的token解析器,能进到这里的说明肯定有token,没token的已经被security处理了
         */
        doFilter(request, response, filterChain);

    }
}
